package com.cskaoyan.user.service.impl;

import com.cskaoyan.mall.commons.exception.ExceptionProcessorUtils;
import com.cskaoyan.mall.commons.exception.ValidateException;
import com.cskaoyan.user.constants.UserRetCode;
import com.cskaoyan.user.dal.entitys.Member;
import com.cskaoyan.user.dal.entitys.UserVerify;
import com.cskaoyan.user.dal.persistence.MemberMapper;
import com.cskaoyan.user.dal.persistence.UserVerifyMapper;
import com.cskaoyan.user.dto.UserVerifyRequest;
import com.cskaoyan.user.dto.UserVerifyResponse;

import com.cskaoyan.user.service.IUserVerifyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;

/**
 * @ClassName: IUserVerifyServiceImpl
 * @Author: wangjinbo
 **/
@Service
@Transactional
public class IUserVerifyServiceImpl implements IUserVerifyService {
    @Autowired
    UserVerifyMapper userVerifyMapper;
    @Autowired
    MemberMapper memberMapper;

    @Override
    public UserVerifyResponse updateVerify(UserVerifyRequest userVerifyRequest) {
        UserVerifyResponse response = new UserVerifyResponse();
        try {
            userVerifyRequest.requestCheck();
            // 更改verify表
            Example example = new Example(UserVerify.class);
            example.createCriteria()
                    .andEqualTo("username", userVerifyRequest.getUserName())
                    .andEqualTo("uuid", userVerifyRequest.getUuid());
            UserVerify userVerify = new UserVerify();
            userVerify.setRegisterDate(new Date());
            userVerify.setIsExpire("N");
            userVerify.setIsVerify("Y");
            int i = userVerifyMapper.updateByExampleSelective(userVerify, example);
            if (i != 1) {
                throw new ValidateException(UserRetCode.USERVERIFY_INFOR_INVALID.getCode(), UserRetCode.USERVERIFY_INFOR_INVALID.getMessage());
            }
            // 更改member表
            Example example2 = new Example(UserVerify.class);
            example2.createCriteria()
                    .andEqualTo("username", userVerifyRequest.getUserName());
            Member member = new Member();
            member.setUpdated(new Date());
            member.setIsVerified("Y");
            int updateMember = memberMapper.updateByExampleSelective(member, example2);
            if (updateMember != 1) {
                throw new ValidateException(UserRetCode.USERVERIFY_INFOR_INVALID.getCode(), UserRetCode.USERVERIFY_INFOR_INVALID.getMessage());
            }
            response.setCode(UserRetCode.SUCCESS.getCode());
            response.setMsg(UserRetCode.SUCCESS.getMessage());
        } catch (Exception e) {
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }
        return response;

    }
}
